package com.sinotrans.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NetWorkUtil {

	/**
	 * 下载网络文件
	 * 
	 * @param link
	 * @return
	 * @throws MalformedURLException
	 */
	public static String downloadNetFile(final String link) throws MalformedURLException {
		System.out.println("link: " + link);
		URL url = new URL(link);
		String saveFile = link;
		saveFile = saveFile.replace("http://", "/");
		saveFile = saveFile.replace("https://", "/");
		int index = 0;
		saveFile = "." + saveFile.substring(index, saveFile.length());
		index = saveFile.lastIndexOf('/');
		File dir = new File(saveFile.substring(0, index));
		if (!dir.exists()) {
			dir.mkdirs();
		}
		if (saveFile.endsWith("/")) {
			saveFile += "index.html";
		}
		try {
			URLConnection conn = url.openConnection();
			InputStream inStream = conn.getInputStream();
			FileOutputStream fs = new FileOutputStream(saveFile);
			byte[] buffer = new byte[1204];
			int byteread = 0;
			while ((byteread = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, byteread);
			}
			fs.flush();
			fs.close();
			inStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		downloadChildFile(link, saveFile);
		return saveFile;
	}

	private static void downloadChildFile(String link, String htmlFile) {
		try {
			if (htmlFile.endsWith(".html")) {
				BufferedReader br = new BufferedReader(new FileReader(htmlFile));
				String line = null;
				while ((line = br.readLine()) != null) {
					String href = aHrefValue(line);
					if (href != null && !href.startsWith("../")) {
						if (!href.startsWith("http://") && !href.startsWith("https://")) {
							href = link + href;
						}
						String childHtml = downloadNetFile(href);
						downloadChildFile(href, childHtml);
					}
				}
				br.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String aHrefValue(String s) {
		String regex = "(?i)<a[^>]*?href=\"([^\"]*)\"[^>]*>";
		Pattern pattern = Pattern.compile(regex);
		String href = null;
		Matcher matcher = pattern.matcher(s);
		if (matcher.find()) {
			href = matcher.group(1);
		}
		return href;
	}

	static void test() throws Exception {
		String netdir = "https://dbeaver.io/update/latest/";
		NetWorkUtil.downloadNetFile(netdir);
	}

}
